// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package verify

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib/authorizer"
)

// Logic
// 校验二维码.
type Logic struct {
	auth     *authorizer.Authentication
	qrcode   *models.Qrcode
	request  *Request
	response *Response
}

// New
// 创建逻辑.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
//
//  1. 入参校验
//  2. 身份鉴权
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 业务处理.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err           error
		has           bool
		qrcodeService = services.NewQrcodeService()
		res           = result.New()
	)

	// 1. 查询二维码.
	if o.qrcode, has, err = qrcodeService.Dao.GetById(ctx, o.request.QrcodeId); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 无效二维码.
	//    二维码不存在或签名错误.
	if !has || o.qrcode.Sign != o.request.QrcodeSign {
		return res.WithError(errs.ErrQrcodeNotFound)
	}

	// 3. 可用检查.
	if _, err = o.qrcode.CanUse(); err != nil {
		return res.WithError(err)
	}

	// 4. 事务处理.
	if err = o.RunScanner(ctx); err != nil {
		return res.WithError(err)
	}

	// 5. 返回结果.
	return res.With(o.response.With(o.qrcode))
}

func (o *Logic) RunScanner(ctx context.Context) error {
	return db.Transaction(ctx,
		o.RunScannerInsert,
		o.RunScannerUpdate,
	)
}

func (o *Logic) RunScannerInsert(ctx context.Context, sess *db.Session) (err error) {
	if _, err = services.NewQrcodeScannerService(sess).Dao.AddByStruct(ctx, &models.QrcodeScanner{
		QrcodeId: o.qrcode.Id,
		UserId:   o.auth.UserId,
	}); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

func (o *Logic) RunScannerUpdate(ctx context.Context, sess *db.Session) (err error) {
	var affects int64
	if affects, err = services.NewQrcodeService(sess).UpdateScannedCount(ctx, o.qrcode); err == nil && affects > 0 {
		o.qrcode.ScannedCount++
	}
	return
}
